package org.jfk.sys.menu;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jfk.core.model.BaseModel;
import org.jfk.core.model.SqlFilter;
import org.jfk.core.utils.SqlFileUtils;
import org.jfk.sys.role.Role;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

public class Menu extends BaseModel<Menu>{

	private static Logger logger = Logger.getLogger(Menu.class);	
	public static final Menu dao;
	public static final Table table;
	public static final String tableName;

	static {
		dao = new Menu();
		table = TableMapping.me().getTable(Menu.class);
		tableName = table.getName();
	}
	
	public Page<Menu> paginate(MenuController controller){
		String select = "SELECT aa.*, "
				+ " CONCAT(REPEAT('&emsp;', countStr(path, ',') * 2), aa.name) AS show_name, "
				+ " countStr(path, ',') AS path_level, countStr(children, ',') AS children_count, "
				+ " CONCAT(REPEAT('&emsp;', countStr(path, ',') * 2), aa.order_num) AS order_num_show";

		String from = " FROM (SELECT a.*, getMenuShowOrder(id) AS path, getMenuChldIds(id) AS children "
				+ "FROM "+tableName+" a ORDER BY path asc, order_num asc) aa";
		String where = " where 1=1 ";
		
		SqlFilter filter = controller.genJsonFilter();
		
		//处理列表查询的智能搜索
		String search = controller.getPara("search");	

		if (search != null && !"".equals(search.trim())) {
			SqlFilter searchFilter = new SqlFilter();
			searchFilter.add("and", "id", "eq", search);
			searchFilter.add("or", "name", "like", search);
			searchFilter.add("or", "url", "like", search);
			searchFilter.end();
			filter.add(searchFilter);
			controller.setAttr("search", search);
		}
		
		//加工request参数
		controller.addPageAttr();
		
		String sqlExceptSelect = from+where+filter.sqlText;
		sqlExceptSelect = sqlExceptSelect + " order by path";
		logger.debug(filter);
		Page<Menu> page = dao.paginate(controller.currentPage, controller.limit, select, sqlExceptSelect, filter.params.toArray());
		return page;
	}
	
	public Menu findById(Object id){
		return super.findById(id);
	}
	
	public Menu loadByRoot(){
		Menu root = super.findById(1);
		root.put("children",loadChildren(root));
		return root;
	}
	
	public List<Menu> loadChildren(Menu menu){
		List<Menu> children = new ArrayList<Menu>();
		if (menu == null){
			return children;
		}
		children = super.find("select * from "+tableName+" where type <> 100403 and pid = ? order by order_num",menu.get("id"));
		for (int i = 0  ; i < children.size() ; i++){
			Menu submenu = children.get(i);
			submenu.put("children",loadChildren(submenu));
		}
		return children;
	}
	
	/**
	 * 根据用户角色获取菜单
	 * @param userId
	 * @return
	 */
	public Menu loadByRoot(int userId){
		
		if (Role.dao.isAdmin(userId)){
			return loadByRoot();
		}
		
		Menu root = super.findById(1);
		List<Menu> children = loadChildren(root,userId);
		
		
		//除去无下级的非叶子节点
		for (int i = 0 ; i < children.size() ; i++){
			Menu tmenu = children.get(i);
			if (tmenu.get("children") == null && tmenu.get("url") == null){
				children.remove(i);
				
				//因为remove，必须进行的调整
				i--;
				
			}
		}
		
		if (children != null && children.size() > 0)
			root.put("children",children);
		return root;
	}
	
	/**
	 * 根据用户角色获取菜单
	 * @param menu
	 * @param userId
	 * @return
	 */
	public List<Menu> loadChildren(Menu menu,int userId){
		List<Menu> children = new ArrayList<Menu>();
		if (menu == null){
			return children;
		}
		//children = super.find("select * from "+tableName+" where pid = ? order by order_num",menu.get("id"));
		
//		String select = "select * from sys_menu where "
//				+ "(url is null or url = '/#' "
//				+ " or url in (select url from view_sys_urls a inner join sys_role_url b on a.id = b.url_id and b.role_id "
//				+ " in (select role from sys_user_role c where c.user_info = ?))) "
//				+ " and status = 3200 and pid = ? order by order_num";	
		
		String select = SqlFileUtils.readSqlFromFile("sys.loadChildren.sql");
		children = super.find(select,userId,menu.get("id"));
		for (int i = 0  ; i < children.size() ; i++){
			Menu submenu = children.get(i);
			List<Menu> children2 = loadChildren(submenu,userId);
			
			//除去无下级的非叶子节点
			for (int j = 0 ; j < children2.size() ; j++){
				Menu tmenu = children2.get(j);
				if (tmenu.get("children") == null && tmenu.get("url") == null){
					children2.remove(j);
					
					//因为remove，必须进行的调整
					j--;
				}
			}
			
			if (children != null && children2.size() > 0){
				submenu.put("children",children2);
			}
		}
		return children;
		
	}	
}
